package cn.catsdad.service.impl;

import cn.catsdad.auth.context.AuthenticationContextHolder;
import cn.catsdad.auth.service.TokenService;
import cn.catsdad.dto.UserDTO;
import cn.catsdad.service.api.LoginService;
import cn.catsdad.vo.LoginParams;
import cn.catsdad.vo.LoginUser;
import cn.catsdad.vo.ResponseUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

/**
 * 登录service实现
 *
 * @author xuyonglong
 * @version V1.0 2023/4/10
 */
@Service
public class LoginServiceImpl implements LoginService {

    private AuthenticationManager authenticationManager;
    private TokenService tokenService;

    @Override
    public ResponseUser login(LoginParams loginParams) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginParams.getUserName(), loginParams.getPassword());
        AuthenticationContextHolder.setContext(authenticationToken);
        //调用UserDetailsServiceImpl进行验证操作
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String token = tokenService.createToken(loginUser);
        //创建返回前端的用户传输对象并返回
        return createResponseUser(loginUser, token);
    }

    /**
     * 创建返回前端的用户传输对象
     *
     * @param loginUser 登录用户
     * @param token     生成的token
     * @return 用户信息传输对象
     */
    private static ResponseUser createResponseUser(LoginUser loginUser, String token) {
        UserDTO result = new UserDTO();
        BeanUtils.copyProperties(loginUser.getUser(), result);
        result.setPassword("");
        return new ResponseUser()
                .setUserId(loginUser.getUserId())
                .setToken(token)
                .setDepartmentId(loginUser.getDepartmentId())
                .setDepartmentName(loginUser.getDepartmentName())
                .setMenuList(loginUser.getMenuList())
                .setUser(result);
    }

    @Autowired
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Autowired
    public void setTokenService(TokenService tokenService) {
        this.tokenService = tokenService;
    }
}
